using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;

using LogAnalyzer.Grabbers;

namespace LogAnalyzer.Dialogs
{
    public partial class Main : Form
    {
        private List<SingleViewer> _viewers;

        public Main()
        {
            InitializeComponent();
            _viewers = new List<SingleViewer>();
        }


        private void Main_Load(object sender, EventArgs e)
        {
            CheckCurrentLanguage();
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            for (int i = _viewers.Count - 1; i >= 0; i--)
            {
                _viewers[0].Close();
            }
        }

        #region Menu

        private void newViewerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewViewer();
        }
        private void saveWorkspaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.CheckPathExists = true;
                sfd.DefaultExt = "lnz";
                sfd.Filter = Globalization.ResourceManager.Current.GetString("DLG_WS_LAW_FILE_DESC") + " (*.law)|*.law";
                sfd.OverwritePrompt = true;
                sfd.Title = Globalization.ResourceManager.Current.GetString("DLG_WS_SAVE_TITLE");
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string fileName = sfd.FileName;
                    if (File.Exists(fileName))
                        File.Delete(fileName);

                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml("<?xml version=\"1.0\"?><logAnalyzer></logAnalyzer>");
                    foreach (SingleViewer sv in _viewers)
                    {
                        XmlNode nodeSingleViewer = xml.CreateElement("singleViewer");
                        sv.SaveConfig(nodeSingleViewer);
                        xml.SelectSingleNode("/logAnalyzer").AppendChild(nodeSingleViewer);
                    }
                    xml.Save(fileName);
                }
            }
        }
        private void loadWorkspaceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists = true;
                ofd.Filter = Globalization.ResourceManager.Current.GetString("DLG_WS_LAW_FILE_DESC") + " (*.law)|*.law";
                ofd.Multiselect = false;
                ofd.Title = Globalization.ResourceManager.Current.GetString("DLG_WS_OPEN_TITLE");
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    LoadWorkSpace(ofd.FileName);
                }
            }
        }
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (About frm = new About())
            {
                frm.ShowDialog();
            }
        }
        private void tileverticallyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileVertical);
        }
        private void tilehorizontallyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.TileHorizontal);
        }
        private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.Cascade);
        }
        private void arrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LayoutMdi(MdiLayout.ArrangeIcons);
        }
        private void italianoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetNewUILanguege("IT");
        }
        private void englishToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetNewUILanguege("EN");
        }

        #endregion

        #region Methods

        private void NewViewer()
        {
            using (Dialogs.NewViewer frmNew = new NewViewer())
            {
                string selGrabber = null;
                while (string.IsNullOrEmpty(selGrabber))
                {
                    switch (frmNew.ShowDialog())
                    {
                        case DialogResult.OK:
                            selGrabber = frmNew.SelectedGrabberType;
                            if (string.IsNullOrEmpty(selGrabber))
                            {
                                MessageBox.Show(
                                    Globalization.ResourceManager.Current.GetString("SELECT_GRABBER_PROMPT"),
                                    this.Text,
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                            break;

                        default:
                            return;
                    }
                }

                try
                {
                    CreateNewViewer(selGrabber, null);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(
                        Globalization.ResourceManager.Current.GetString("CREATE_VIEWER_ERROR", ex.Message),
                        this.Text,
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        private void CreateNewViewer(string grabber, string fileGrabberFileName)
        {
            Type grabberType = Type.GetType(grabber);
            if (grabber == null)
                return;

            GrabberBase grabberObj = (GrabberBase)Activator.CreateInstance(grabberType);
            if (!string.IsNullOrEmpty(fileGrabberFileName))
            {
                grabberObj.Config.Add("fileGrabber.fileName", fileGrabberFileName);
            }

            if (grabberObj.ShowConfigDialog() == DialogResult.OK)
            {
                SingleViewer viewer = new SingleViewer(grabberObj, this);
                AddInViewerList(viewer);
                viewer.Show();
            }
        }

        private void LoadWorkSpace(string sourceFile)
        {
            XmlDocument xml = new XmlDocument();
            try
            {
                xml.Load(sourceFile);

                if (_viewers != null && _viewers.Count > 0)
                {
                    if (MessageBox.Show(Globalization.ResourceManager.Current.GetString("CLOSE_OPENED_VIEWERS_ASK"),
                        Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                        == DialogResult.Yes)
                    {
                        SingleViewer[] viewers = _viewers.ToArray();
                        foreach (SingleViewer sv in viewers)
                        {
                            sv.Close();
                        }
                        viewers = null;
                    }
                }

                foreach (XmlNode nodeSv in xml.SelectNodes("/logAnalyzer/singleViewer"))
                {
                    SingleViewer viewer = new SingleViewer(null, this);
                    viewer.LoadConfig(nodeSv);
                    AddInViewerList(viewer);
                    viewer.Show();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    "Cannot load workspace file!\r\n\r\n" + ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void AddInViewerList(SingleViewer v)
        {
            _viewers.Add(v);
            v.FormClosing +=
                new FormClosingEventHandler(SingleViewer_FormClosing);
            saveWorkspaceToolStripMenuItem.Enabled = true;
            tilehorizontallyToolStripMenuItem.Enabled = true;
            tileverticallyToolStripMenuItem.Enabled = true;
            cascadeToolStripMenuItem.Enabled = true;
            arrangeIconsToolStripMenuItem.Enabled = true;
        }
        private void RemoveFromViewerList(SingleViewer v)
        {
            lock (_viewers)
            {
                if (_viewers.Contains(v))
                    _viewers.Remove(v);

                if (_viewers.Count == 0)
                {
                    saveWorkspaceToolStripMenuItem.Enabled = false;
                    tilehorizontallyToolStripMenuItem.Enabled = false;
                    tileverticallyToolStripMenuItem.Enabled = false;
                    cascadeToolStripMenuItem.Enabled = false;
                    arrangeIconsToolStripMenuItem.Enabled = false;
                }
            }
        }
        private void SingleViewer_FormClosing(object sender, FormClosingEventArgs e)
        {
            SingleViewer closingViewer = (SingleViewer)sender;
            RemoveFromViewerList(closingViewer);
        }

        private void SetNewUILanguege(string language)
        {
            Globalization.ResourceManager.SetCulture(language);
            Invalidate();
            CheckCurrentLanguage();
        }
        private void CheckCurrentLanguage()
        {
            switch (Globalization.ResourceManager.Current.Culture.TwoLetterISOLanguageName.ToUpper())
            {
                case "IT":
                    italianoToolStripMenuItem.Checked = true;
                    englishToolStripMenuItem.Checked = false;
                    break;
                case "EN":
                    italianoToolStripMenuItem.Checked = false;
                    englishToolStripMenuItem.Checked = true;
                    break;
            }
        }

        #endregion

        #region Drag&Drop

        private void Main_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Move;
            else
                e.Effect = DragDropEffects.None;
        }
        private void Main_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
            LoadFiles(files);
        }

        #endregion

        internal void LoadFiles(string[] files)
        {
            foreach (string file in files)
            {
                if (file.Length < 4)
                    continue;

                string ext = new FileInfo(file).Extension;
                switch (ext)
                {
                    case ".law":
                        LoadWorkSpace(file);
                        return;
                    case "":
                        if (Directory.Exists(file))
                            CreateNewViewer("LogAnalyzer.Grabbers.FileGrabber", file);
                        break;
                    case ".log":
                    case ".txt":
                        CreateNewViewer("LogAnalyzer.Grabbers.FileGrabber", file);
                        break;
                    default:
                        MessageBox.Show(Globalization.ResourceManager.Current.GetString("UNKNOWN_EXTENSION") + " (" + ext + ")", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        break;
                }
            }
        }

    }
}